package com.class5.springboot.frame.util.kengen;

import java.net.InetAddress;
import java.net.UnknownHostException;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class KeyGeneratorFactory {
    private static DefaultKeyGenerator keygen = null;

    /**
     * 生成一个唯一的序列号
     *
     * @return
     */
    public static synchronized Long generateKey() {
        if (keygen == null) {
            initKeyGen();
        }
        return (Long) keygen.generateKey();
    }

    // 初始化序列生成器
    private static void initKeyGen() {
        // 根据IP地址来生成workId
        InetAddress address;
        try {
            address = InetAddress.getLocalHost();
        } catch (final UnknownHostException e) {
            throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!");
        }
        log.info("Current workid generate from ip:{}", address);
        byte[] ipAddressByteArray = address.getAddress();
        long workerId = 0L;
        // IPV4
        if (ipAddressByteArray.length == 4) {
            for (byte byteNum : ipAddressByteArray) {
                workerId += byteNum & 0xFF;
            }
            // IPV6
        } else if (ipAddressByteArray.length == 16) {
            for (byte byteNum : ipAddressByteArray) {
                workerId += byteNum & 0B111111;
            }
        } else {
            throw new IllegalStateException("Bad LocalHost InetAddress, please check your network!");
        }
        DefaultKeyGenerator.setWorkerId(workerId);

        keygen = new DefaultKeyGenerator();
    }
}
